<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>快乐星球</title>
    <link rel="stylesheet" href="static/icon.css">
    <link href="static/material-components-web.min.css" rel="stylesheet">
    <!-- <link href="static/iconfont/iconfont.css" rel="stylesheet"> -->
    <script src="static/iconfont/iconfont.js?date=new"></script>
    <!-- <link href="static/example.css" rel="stylesheet"> -->
    <link href="static/ourintegral.css?date=new" rel="stylesheet">
    <script src="static/material-components-web.min.js"></script>
    <script type="text/javascript" src="http://cdn.jsdelivr.net/npm/eruda"></script>

    <style>
        .my-card__media_test {
            background-image: url("static/img/love1.jpg");
        }

        .my-card__media_exercise {
            background-image: url("static/img/love3.jpg");
        }

        .my-card__media_project {
            background-image: url("static/img/love2.jpg");
        }
    </style>
</head>

<body>
    <div class="test_zone_disabled">
        <div class="mdc-tab-bar" role="tablist">
            <div class="mdc-tab-scroller">
                <div class="mdc-tab-scroller__scroll-area">
                    <div class="mdc-tab-scroller__scroll-content">
                        <button class="mdc-tab mdc-tab--active" role="tab" aria-selected="true" tabindex="1">
                            <span class="mdc-tab__content">
                                <span class="mdc-tab__icon material-icons" aria-hidden="true">task_alt</span>
                                <span class="mdc-tab__text-label">GetScore</span>
                            </span>
                            <span class="mdc-tab-indicator mdc-tab-indicator--active">
                                <span class="mdc-tab-indicator__content mdc-tab-indicator__content--underline"></span>
                            </span>
                            <span class="mdc-tab__ripple"></span>
                        </button>
                        <button class="mdc-tab" role="tab" aria-selected="false" tabindex="2">
                            <span class="mdc-tab__content">
                                <span class="mdc-tab__icon material-icons" aria-hidden="true">shopping_bag</span>
                                <span class="mdc-tab__text-label">Overview</span>
                            </span>
                            <span class="mdc-tab-indicator">
                                <span class="mdc-tab-indicator__content mdc-tab-indicator__content--underline"></span>
                            </span>
                            <span class="mdc-tab__ripple"></span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div id="getscore-section">
        <div class="cn-banner">
        </div>
        <ul class="mdc-list fixed_items_zone">
        </ul>
        <div class="self-input-zone mdc-dialog mdc-dialog--fullscreen">
            <div class="mdc-dialog__container">
                <div class="mdc-dialog__surface" role="dialog" aria-modal="true" aria-labelledby="my-dialog-title"
                    aria-describedby="my-dialog-content">
                    <div class="mdc-dialog__header">
                        <h2 class="mdc-dialog__title" id="my-dialog-title">
                            爱你爱的深沉
                        </h2>
                        <button class="mdc-icon-button material-icons mdc-dialog__close" data-mdc-dialog-action="close">
                            close
                        </button>
                    </div>
                    <div class="mdc-dialog__content" id="my-dialog-content">
                        <div style="margin-bottom: 10px;" class="common_card">
                            <label class="mdc-text-field mdc-text-field--outlined reason_text self_text_input">
                                <span class="mdc-notched-outline">
                                    <span class="mdc-notched-outline__leading"></span>
                                    <span class="mdc-notched-outline__notch">
                                        <span class="mdc-floating-label" id="addscore-reason-label">加分理由</span>
                                    </span>
                                    <span class="mdc-notched-outline__trailing"></span>
                                </span>
                                <input type="text" id="addscore-reason" class="mdc-text-field__input"
                                    aria-labelledby="addscore-reason-label">
                            </label>
                            <label class="mdc-text-field mdc-text-field--outlined addscore_text self_text_input">
                                <span class="mdc-notched-outline">
                                    <span class="mdc-notched-outline__leading"></span>
                                    <span class="mdc-notched-outline__notch">
                                        <span class="mdc-floating-label" id="addscore-value-label">加分数值</span>
                                    </span>
                                    <span class="mdc-notched-outline__trailing"></span>
                                </span>
                                <input type="text" id="addscore-value" class="mdc-text-field__input"
                                    aria-labelledby="addscore-value-label">
                            </label>
                            <div class="common_button_wrapper">
                                <button type="button" class="mdc-button mdc-button--raised mdc-dialog__button"
                                    data-mdc-dialog-action="ok" id="do-free-add">
                                    <div class="mdc-button__ripple"></div>
                                    <i class="material-icons mdc-button__icon" aria-hidden="true">task_alt</i>
                                    <span class="mdc-button__label">确认</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="mdc-dialog__scrim"></div>
        </div>
        <div class="mdc-dialog fixed_item_input">
            <div class="mdc-dialog__container">
              <div class="mdc-dialog__surface"
                role="alertdialog"
                aria-modal="true"
                aria-labelledby="my-dialog-title"
                aria-describedby="my-dialog-content">
                <h3 class="mdc-dialog__title" id="my-dialog-title">让我康康乖不乖🤔</h3>
                <div class="mdc-dialog__content" id="my-dialog-content">
                    <div style="margin-bottom: 10px;" class="common_card">
                        <label class="mdc-text-field mdc-text-field--outlined reason_text self_text_input fixed_self_input">
                            <span class="mdc-notched-outline">
                                <span class="mdc-notched-outline__leading"></span>
                                <span class="mdc-notched-outline__notch">
                                    <span class="mdc-floating-label" id="addscore-reason-label">加分理由</span>
                                </span>
                                <span class="mdc-notched-outline__trailing"></span>
                            </span>
                            <input type="text" id="fixed_add_reason" class="mdc-text-field__input"
                                aria-labelledby="addscore-reason-label">
                        </label>
                        <label class="mdc-text-field mdc-text-field--outlined addscore_text self_text_input fixed_self_input">
                            <span class="mdc-notched-outline">
                                <span class="mdc-notched-outline__leading"></span>
                                <span class="mdc-notched-outline__notch">
                                    <span class="mdc-floating-label" id="addscore-value-label">加分数值</span>
                                </span>
                                <span class="mdc-notched-outline__trailing"></span>
                            </span>
                            <input type="text" id="fixed_add_value" class="mdc-text-field__input"
                                aria-labelledby="addscore-value-label">
                        </label>
                        <div class="common_button_wrapper">
                            <button type="button" class="mdc-button mdc-button--outlined mdc-dialog__button"
                                data-mdc-dialog-action="cancel">
                                <div class="mdc-button__ripple"></div>
                                <i class="material-icons mdc-button__icon" aria-hidden="true">highlight_off</i>
                                <span class="mdc-button__label">取消</span>
                            </button>
                            <button type="button" class="mdc-button mdc-button--raised mdc-dialog__button"
                                data-mdc-dialog-action="" id="do-fixed-add">
                                <div class="mdc-button__ripple"></div>
                                <i class="material-icons mdc-button__icon" aria-hidden="true">check_circle_outline</i>
                                <span class="mdc-button__label">确认</span>
                            </button>
                        </div>
                    </div>
                </div>
              </div>
            </div>
            <div class="mdc-dialog__scrim"></div>
          </div>
        <div class="common_button_wrapper">
            <button class="mdc-button mdc-button--raised" id="add_score_btn">
                <div class="mdc-button__ripple"></div>
                <i class="material-icons mdc-button__icon" aria-hidden="true">emoji_emotions</i>
                <span class="mdc-button__label">随心记</span>
            </button>
        </div>
    </div>
    <div id="overview-section" style="display: none">
        <div class="basic-info">
            <span class="basic-info-nick">╰(￣▽￣)╭ 欢迎！<span id="info-nick-name"></span></span>
            
        </div>
        <div class="mdc-card">
            <div class="my-card__media_project mdc-card__media mdc-card__media--16-9">
                <div class="mdc-card__media-content">
                </div>
            </div>
            <div class="mdc-card__content my-card">
                <div>
                    <span id="say-one-sentence" style="text-indent: 2em"></span>
                </div>
                <div class="score-zone">
                    <span class="basic-info-score">
                        <svg class="icon" aria-hidden="true">
                            <use id="self_icon" xlink:href="#icon-male"></use>
                        </svg>
                        <span>&nbsp;&nbsp;</span>
                        <span id="info-self-score"></span>
                    </span>
                    <svg class="icon" aria-hidden="true" onclick='seehistory()'>
                        <use id="self_icon" xlink:href="#icon-jifen"></use>
                    </svg>
                    
                    <span class="basic-info-score">
                        <svg class="icon" aria-hidden="true">
                            <use id="binding_icon" xlink:href="#icon-female"></use>
                        </svg>
                        <span>&nbsp;&nbsp;</span>
                        <span id="info-binding-score"></span>
                    </span>
                </div>
                
            </div>
        </div>
        <div class="card-zone" id="rewards-list">
                    
        </div>
        <div class="mdc-dialog history-dialog">
            <div class="mdc-dialog__container">
              <div class="mdc-dialog__surface"
                role="alertdialog"
                aria-modal="true"
                aria-labelledby="my-dialog-title"
                aria-describedby="my-dialog-content">
                <h3 class="mdc-dialog__title" style="text-align: center;" tabindex="10">🐱👮‍</h3>
                <div class="mdc-dialog__content" id="history-content">
                  <ul class="mdc-list history-list">
                    
                  </ul>
                </div>
              </div>
            </div>
            <div class="mdc-dialog__scrim"></div>
          </div>

    </div>
    <aside class="mdc-snackbar">
        <div class="mdc-snackbar__surface" role="status" aria-relevant="additions">
            <div class="mdc-snackbar__label" aria-atomic="false" id="snackbar-content">
                填写所有内容哦~
            </div>
            <div class="mdc-snackbar__actions" aria-atomic="true">
                <button type="button" class="mdc-button mdc-snackbar__action">
                    <div class="mdc-button__ripple"></div>
                    <span class="mdc-button__label">知道了</span>
                </button>
            </div>
        </div>
    </aside>
    <pre id="login_info" style="margin-bottom: 20px;">
</pre>
    <pre id="displayEle">
    </pre>
    <div id="common-part">
    </div>
    <div style="text-align: center; font-size: 0.7em; color: lightslategray;" onclick="this.style.visibility = this.style.visibility=='hidden' ? 'initial' : 'hidden'">
        @Latest: 21/08/21 11:51
    </div>

    <script src='dist/gitdb.bundle.js'></script>
    <script src='dist/ourintegral.bundle.js'></script>
    <script>
        var test = false;
        var ADD_TYPE = 'FIXED'; // FIXED / FREE
        var CURRENT_CHOOSE_FIXED_ITEM_INDEX = 0;
        const {MDCSnackbar} = mdc.snackbar
        const snackbar = new MDCSnackbar(document.querySelector('.mdc-snackbar'));
        const simpleNotify = (message) => {
            const ele = document.getElementById("snackbar-content")
            ele.innerHTML = message;
            snackbar.open();
        }

        // 奖励区初始化 BEGIN
        const genOneAward = (data) => {
            return `<div class="one-card" onclick="simpleNotify('${data.desc}')">
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="${data.icon ? data.icon : '#icon-ticket_integral'}"></use>
                        </svg>
                        <span class="one-card-score">${data.score ? data.score : 100}</span>
                    </div>`
        }
        const rewardsList = document.getElementById("rewards-list")
        const initialRewards = () => {
            let {rewards} = ourintegral.globalData
            let rewardsHtml = ""
            rewards.forEach(reward => {
                rewardsHtml += genOneAward(reward)
            })
            rewardsList.innerHTML = rewardsHtml
        }
        // 奖励区初始化 END

        const { MDCTooltip } = mdc.tooltip;
        const { MDCTabBar } = mdc.tabBar;
        const { MDCRipple } = mdc.ripple;
        const { MDCList } = mdc.list;
        const { MDCTextField } = mdc.textField;
        const { MDCDialog } = mdc.dialog;

        const tabBar = new MDCTabBar(document.querySelector('.mdc-tab-bar'));
        const buttonRipple = new MDCRipple(document.querySelector('.mdc-button'));
        const scorePart = document.querySelector("#getscore-section")
        const overviewPart = document.querySelector("#overview-section")
        const sectionArr = [scorePart, overviewPart]
        const switchSection = (sectionId) => {
            if (sectionId > sectionArr.length - 1 || sectionId < 0) {
                throw Error("error section id")
            }
            sectionArr.forEach((section, index) => {
                if (index !== sectionId) {
                    section.style.display = 'none'
                } else {
                    section.style.display = 'block'
                }
            })
        }
        document.querySelector('.mdc-tab-bar').addEventListener("MDCTabBar:activated", event => {
            // console.log('current choosed:', event.detail)
            switchSection(event.detail.index)
            if (event.detail.index === 1) {
                setOverview();
            }
        })

        const nickEle = document.getElementById("info-nick-name")
        var hideVar = 0;
        nickEle.addEventListener("click", (e) => {
            hideVar++;
            if (hideVar === 5) {
                eruda.init()
            }
        })

        // {userId: userInfo}
        var currentBothData = {}
        var genderIconMap = {
            "male": "#icon-male",
            "female": "#icon-female",
        }
        const setOverview = () => {
            const { login: currentUser } = ourintegral.globalData
            nickEle.innerHTML = currentUser.nickName
            ourintegral.Overview.getBothScoreLatest().then(bothData => {
                let {currentUserInfo, bindingUserInfo} = bothData;
                document.getElementById("self_icon").setAttribute("xlink:href", genderIconMap[currentUserInfo.gender])
                document.getElementById("info-self-score").innerHTML = currentUserInfo.score

                document.getElementById("binding_icon").setAttribute("xlink:href", genderIconMap[bindingUserInfo.gender])
                document.getElementById("info-binding-score").innerHTML = bindingUserInfo.score

                currentBothData[currentUserInfo.id] = currentUserInfo
                currentBothData[bindingUserInfo.id] = bindingUserInfo
            }).catch(e => {
                simpleNotify(e.message)
            })
            
        }

        const addScoreKeys = ['userId', 'integral', 'source', 'sourceType']
        const addScore = async (data) => {
            addScoreKeys.forEach(v => {
                if (data[v] === undefined || data[v] === '') {
                    throw Error(`add score data not integrated for key:${v}`)
                }
            })
            console.log('add score:', data)
            // return
            try {
                await ourintegral.HistoryOperation.addOne(data)
                await ourintegral.UserOperation.addScore(data.userId, data.integral)
                simpleNotify("😋一番操作终成功~")
            } catch (e) {
                console.error('Add Score Failure, Need rollback, but now can not do this.')
                console.error(e)
                simpleNotify(e.message)
            } finally {
                // freeInputDialog.close()
            }
        }
        const addFixedScore = async (item) => {
            let data = {}
            data.userId = ourintegral.globalData.login.id
            data.integral = parseFloat(item.score)
            data.source = item.source ? item.source : `${item.itemName}[${item.id}]`
            data.sourceType = `fixed[${item.type}]`
            await addScore(data)
        }
        const addFreeScore = async (e) => {
            let reason = document.getElementById("addscore-reason").value
            let score = parseFloat(document.getElementById("addscore-value").value)
            if (!reason || !score) {
                simpleNotify('矮油，没填完的话四不可以滴😁')
                return
            }
            let data = {}
            data.userId = ourintegral.globalData.login.bindingId
            data.integral = score
            data.source = reason
            data.sourceType = 'free'
            await addScore(data)
        }
        const reasonEle = document.querySelector('.reason_text')
        const addScoreEle = document.querySelector('.addscore_text')
        const reasontf = new MDCTextField(reasonEle)
        const addscoretf = new MDCTextField(addScoreEle)
        const freedomAddBtnEle = document.querySelector('#add_score_btn')
        const freedomAddBtn = new MDCRipple(freedomAddBtnEle)
        const freeInputDialog = new MDCDialog(document.querySelector('.self-input-zone'))
        freedomAddBtn.listen("click", () => {
            freeInputDialog.open()
        })
        const doFreeAdd = new MDCRipple(document.getElementById("do-free-add"))
        doFreeAdd.listen("click", addFreeScore)
        

        const fixedInputDialog = new MDCDialog(document.querySelector(".fixed_item_input"))
        fixedInputDialog.scrimClickAction = ""
        document.querySelectorAll(".fixed_self_input").forEach(ele => {
            new MDCTextField(ele)
        })
        const doFixedAdd = document.getElementById("do-fixed-add")
        new MDCRipple(doFixedAdd)
        doFixedAdd.addEventListener("click", async () => {
            let reason = document.querySelector("#fixed_add_reason").value
            let value = parseFloat(document.querySelector("#fixed_add_value").value)
            if (!reason || !value) {
                simpleNotify("🤨我康康，咋没填完")
                return
            }
            try {
                var item = ourintegral.globalData.fixedItems[CURRENT_CHOOSE_FIXED_ITEM_INDEX]
                await addFixedScore({...item, score: value, source: `${item.itemName}-${reason}-[${item.id}]`})
            } catch (e) {
                console.error("fixed add err:", e)
            } finally {
                fixedInputDialog.close()
            }
        })

        const fixedItems = document.querySelector('.fixed_items_zone')
        const fixedItemList = new MDCList(fixedItems)
        fixedItemList.singleSelection = true;
        fixedItemList.listElements.forEach(ele => new MDCRipple(ele))

        const fixedIconMap = {
            "default": "#icon-lightbulb-01",
            "exercise": "#icon-exercise1",
            "sleep": "#icon--sleeping",
            "test": "#icon-hat2"
        }
        const genIconName = (data) => {
            let {type, icon} = data;
            if (icon) {
                return icon;
            } else {
                if (fixedIconMap[type]) {
                    return fixedIconMap[type]
                } else {
                    return fixedIconMap.default
                }
            }
        }
        // {type, itemName, score, enabled, id}
        const genMdcListItem = (data) => {
            const iconName = genIconName(data)
            return `<li class="mdc-list-item my-fixed-item">
                        <span class="mdc-list-item__ripple"></span>
                        <svg class="icon fixed_item_icon" aria-hidden="true">
                            <use xlink:href="${iconName}"></use>
                        </svg>
                        <span class="mdc-list-item__text">${data.itemName}</span>
                        <span class="mdc-list-item__meta">${data.score}</span>
                    </li>`
        }

        const afterSureTask = (taskIndex) => {
            return (event) => {
                if (event.detail.action !== 'ok') {
                    console.log('has canceld!')
                    return
                }
                let taskInfo = ourintegral.globalData.fixedItems[taskIndex]
                switch (taskInfo.type) {
                    case "exercise":
                        fixedInputDialog.open()
                        break;
                    default:
                        addFixedScore(taskInfo)
                }
            }
        }
        fixedItemList.listen("MDCList:action", ({ detail }) => {
            // console.log(`list item ${detail.index} was clicked!`)
            CURRENT_CHOOSE_FIXED_ITEM_INDEX = detail.index;
            ourintegral.showMessage("确认完成该项目?", afterSureTask(detail.index))
        })
        const setListContent = (allData) => {
            let content = '';
            for (item of allData) {
                content += genMdcListItem(item)
            }
            fixedItems.innerHTML = content;
            // listItemsRipple()
        }

        const historyDialog = new MDCDialog(document.querySelector(".history-dialog"))
        const historyListEle = document.querySelector(".history-list")
        const historyList = new MDCList(historyListEle)
        const dealUpdateTime = (timeStr) => {
            let date = new Date(timeStr)
            return `${date.getMonth() + 1}.${date.getDate()} ${date.getHours()}:${date.getMinutes()} `
        }
        const genOneHistoryItem = (data) => {
            return `<li class="mdc-list-item" data-mdc-dialog-action="none">
                      <span class="mdc-list-item__text">
                        ${dealUpdateTime(data.updateTime)} ${data.source.split('[')[0]},给${currentBothData[data.userId].nickName}${data.integral}分</span>
                    </li>`
        }
        const seehistory = async () => {
            let historyArr = await ourintegral.HistoryOperation.getDataByPage({page: 1, per_page: 20})
            let historyHtml = ""
            historyArr.forEach(historyData => {
                // console.log(historyData)
                historyHtml = historyHtml + genOneHistoryItem(historyData)
            })
            historyListEle.innerHTML = historyHtml;
            
            historyDialog.open()
        }
    </script>
    <script>
        const sentenceEle = document.getElementById("say-one-sentence")
        fetch('https://v1.hitokoto.cn/ ').then(resp => resp.json())
            .then(result => {
                sentenceEle.innerHTML = result.hitokoto
            }).catch(e => {
                sentenceEle.innerHTML = 'Only You.'
                console.error("Get One Sentence Err:", e)
            })
    </script>
    <script>
        
        if (!gitdb || !ourintegral) {
            console.error('Please import gitdb and ourintegral module firstly!')
            throw Error('error setting.')
        }

        var settings;

        var fixedList = document.getElementById("fixed_object")
        var allIssue;
        var getAllItems = async () => {
            let items = await ourintegral.FixedItemsOperation.getAll()
            ourintegral.globalData.fixedItems = items;
            setListContent(items)
        }

        window.onload = async () => {
            if (test) {
                return
            }
            try {
                await ourintegral.createApp({ access_token: localStorage.getItem("$ACCESS_TOKEN") });
                await getAllItems();
                initialRewards()
            } catch (e) {
                console.error(e)
            }
        }
    </script>
</body>

</html>